package com.acane.instagram.feature.follow

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.HomeViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun FollowRoute(
    toProfile: (String) -> Unit,
    navController: NavHostController,
    followViewModel: FollowViewModel = viewModel()
) {
    FollowScreen(
        toProfile = toProfile,
        navController = navController,
        followViewModel = followViewModel,
    )
}

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter", "StateFlowValueCalledInComposition")
@Composable
fun FollowScreen(
    toProfile: (String) -> Unit,
    followViewModel: FollowViewModel,
    navController: NavHostController,
    homeViewModel: HomeViewModel = viewModel()
) {
    val isFollowingMap by followViewModel.isFollowingMap.collectAsState() // 收集 isFollowingMap 的状态
    val userInfo = followViewModel.userInfo.collectAsState()

    val pages = listOf("粉丝（${userInfo.value.followerCount}）", "关注（${userInfo.value.followingCount}）")

    val initialPage = when (followViewModel.type) {
        "粉丝" -> 0
        "关注" -> 1
        else -> 0
    }

    val pagerState = com.google.accompanist.pager.rememberPagerState(initialPage = initialPage)

    val coroutineScope = rememberCoroutineScope()



    Scaffold(
        topBar = {
            FollowTopBar(
                navController = navController,
                userInfo = followViewModel.userInfo.value,
            )
        } ,
        containerColor = Color.White,
    ) { padding ->
        Column(
            modifier = Modifier.padding(padding)
        ) {
            TabRow(
                selectedTabIndex = pagerState.currentPage,
                containerColor = Color.Transparent,
                tabs = {
                    pages.forEachIndexed { index, title ->
                        Tab(
                            text = { Text(title) },
                            selected = pagerState.currentPage == index,
                            onClick = {
                                coroutineScope.launch {
                                    pagerState.animateScrollToPage(index)
                                }
                            }
                        )
                    }
                }
            )
            com.google.accompanist.pager.HorizontalPager(
                count = pages.size,
                state = pagerState,
                modifier = Modifier.fillMaxSize()
            ) { page ->
                when (page) {
                    0 -> FollowerScreen(
                        followerUserData = followViewModel.followerList.value,
                        toProfile = toProfile,
                        coroutineScope = coroutineScope,
                        viewModel = followViewModel,
                        homeViewModel = homeViewModel,
                        isFollowingMap = isFollowingMap,
                    )

                    1 -> FollowingScreen(
                        followingUserData = followViewModel.followingList.value,
                        toProfile = toProfile,
                        coroutineScope = coroutineScope,
                        viewModel = followViewModel,
                        homeViewModel = homeViewModel,
                        isFollowingMap = isFollowingMap,
                    )
                }
            }
        }

    }
}

@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun FollowingScreen(
    followingUserData: List<UserInfo>,
    toProfile: (String) -> Unit,
    coroutineScope: CoroutineScope,
    viewModel: FollowViewModel,
    homeViewModel: HomeViewModel,
    isFollowingMap: Map<String, Boolean>,
) {
    val context = LocalContext.current
    if (followingUserData.isEmpty()) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxSize()
        ) {
            Image(
                painter = painterResource(id = R.drawable.plus_user),
                contentDescription = "关注的用户",
                modifier = Modifier
                    .size(200.dp)
                    .padding(top = 50.dp)
            )
            Text(
                text = "你关注的用户",
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                modifier = Modifier.padding(top = 10.dp)
            )
            Text(
                text = "你关注的用户会显示在这里。",
                fontSize = 16.sp,
                color = InstagramDarkGray,
                modifier = Modifier.padding(top = 10.dp)
            )
        }
        return
    }
    LazyColumn(
        modifier = Modifier.fillMaxSize()
    ) {
        items(followingUserData) { followingUser ->
            //val isFollowing by homeViewModel.isFollowing.collectAsState(initial = false)
            val isFollowing = isFollowingMap[followingUser.id] ?: false // 使用 isFollowingMap 获取状态
            // 加载关注状态
            LaunchedEffect(Unit) {
                coroutineScope.launch(Dispatchers.IO) {
                    val isFollowingResponse =
                        homeViewModel.judgeIsFollowed(followingUser.id!!, SessionManager.currentUser?.id)
                    Log.d("UserPostList", "发送请求获得的isFollowingResponse: $isFollowingResponse")
                    viewModel.setIsFollowing(followingUser.id, isFollowingResponse)
                    //homeViewModel.updateIsFollowing(isFollowingResponse)
                }
            }
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 10.dp)
                    .padding(vertical = 8.dp) // 添加统一的上下间距
                    .clickable {
                        // 跳转到对应用户页面
                        toProfile(followingUser.id!!)
                    }
            ) {
                // 头像
                AsyncImage(
                    model = followingUser.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    },
                    contentScale = ContentScale.Crop,
                    contentDescription = "用户头像",
                    modifier = Modifier
                        .size(50.dp)
                        .clip(CircleShape),
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
                Spacer(modifier = Modifier.width(8.dp))
                // 账号以及昵称
                Column(
                    verticalArrangement = Arrangement.Center,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = followingUser.userName ?: "未知用户",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    )
                    Text(
                        text = followingUser.nickName ?: "未知昵称",
                        fontSize = 12.sp,
                        color = InstagramDarkGray
                    )
                }

                if (followingUser.id == SessionManager.currentUser?.id) {
                    // 不显示任何按钮
                } else {
                    // 如果访问的不是当前用户的粉丝列表，则只显示关注与否的按钮
                    if (viewModel.userId != SessionManager.currentUser?.id) {
                        // 关注与否按钮
                        val isFollowed: Boolean = followingUser.id in viewModel.loginFollowingList.value
                        if (isFollowing) {
                            Button(
                                onClick = {
                                    // 发送取消关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendUnFollowRequest(
                                            followingId = SessionManager.currentUser?.id!!,
                                            followerId = followingUser.id!!
                                        )
                                    }
                                    // 提示取消关注成功并更新关注状态
                                    homeViewModel.updateIsFollowing(false)
                                    Toast.makeText(
                                        context,
                                        "取消关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramLightGray,
                                    contentColor = InstagramDarkGray
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "已关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        } else {
                            Button(
                                onClick = {
                                    // 发送关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendFollowRequest(
                                            followingId = SessionManager.currentUser?.id!!,
                                            followerId = followingUser.id!!
                                        )
                                        // 提示关注成功并更新关注状态
                                        homeViewModel.updateIsFollowing(true)
                                    }
                                    Toast.makeText(
                                        context,
                                        "关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramBlue,
                                    contentColor = Color.White
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }

                    } else {
                        if (isFollowing) {
                            // 取消关注按钮
                            Button(
                                onClick = {
                                    // 发送取消关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendUnFollowRequest(
                                            followingId = followingUser.id!!,
                                            followerId = SessionManager.currentUser?.id!!
                                        )
                                        // 提示取消关注成功并更新关注状态
                                        homeViewModel.updateIsFollowing(false)
                                    }
                                    Toast.makeText(
                                        context,
                                        "取消关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramLightGray,
                                    contentColor = InstagramDarkGray
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(100.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "已关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }

//                            Image(
//                                painter = painterResource(id = R.drawable.options_vertical),
//                                contentDescription = "options",
//                                modifier = Modifier.size(24.dp)
//                            )
                        } else {
                            Button(
                                onClick = {
                                    // 发送关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendFollowRequest(
                                            followingId = followingUser.id!!,
                                            followerId = SessionManager.currentUser?.id!!
                                        )
                                        // 提示关注成功并更新关注状态
                                        homeViewModel.updateIsFollowing(true)
                                    }
                                    Toast.makeText(
                                        context,
                                        "关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramBlue,
                                    contentColor = Color.White
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }

                    }

                }

            }
        }
    }
}

@SuppressLint("StateFlowValueCalledInComposition")
@Composable
fun FollowerScreen(
    followerUserData: List<UserInfo>,
    toProfile: (String) -> Unit,
    coroutineScope: CoroutineScope,
    viewModel: FollowViewModel,
    homeViewModel: HomeViewModel,
    isFollowingMap: Map<String, Boolean>,
) {

    val context = LocalContext.current
    if (followerUserData.isEmpty()) {
        Column (
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
            modifier = Modifier.fillMaxSize()
        ) {
            Image(
                painter = painterResource(id = R.drawable.plus_user),
                contentDescription = "粉丝",
                modifier = Modifier
                    .size(200.dp)
                    .padding(top = 50.dp)
            )
            Text(
                text = "粉丝",
                fontWeight = FontWeight.Bold,
                fontSize = 20.sp,
                modifier = Modifier.padding(top = 10.dp)
            )
            Text(
                text = "这里会显示所有关注你的用户。",
                fontSize = 16.sp,
                color = InstagramDarkGray,
                modifier = Modifier.padding(top = 10.dp)
            )
        }
        return
    }
    LazyColumn(
        modifier = Modifier.fillMaxSize()
    ) {
        items(followerUserData) { followerUser ->
            val isFollowing = isFollowingMap[followerUser.id] ?: false // 使用 isFollowingMap 获取状态
            // 加载关注状态
            LaunchedEffect(Unit) {
                coroutineScope.launch(Dispatchers.IO) {
                    val isFollowingResponse =
                        homeViewModel.judgeIsFollowed(followerUser.id!!, SessionManager.currentUser?.id)
                    Log.d("UserPostList", "发送请求获得的isFollowingResponse: $isFollowingResponse")
                    viewModel.setIsFollowing(followerUser.id, isFollowingResponse)
                    //homeViewModel.updateIsFollowing(isFollowingResponse)
                }
            }
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 10.dp)
                    .padding(vertical = 8.dp) // 添加统一的上下间距
                    .clickable {
                        // 跳转到对应用户页面
                        toProfile(followerUser.id!!)
                    }
            ) {
                // 头像
                AsyncImage(
                    model = followerUser.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    },
                    contentScale = ContentScale.Crop,
                    contentDescription = "用户头像",
                    modifier = Modifier
                        .size(50.dp)
                        .clip(CircleShape),
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
                Spacer(modifier = Modifier.width(8.dp))
                // 账号以及昵称
                Column(
                    verticalArrangement = Arrangement.Center,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = followerUser.userName ?: "未知用户",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    )
                    Text(
                        text = followerUser.nickName ?: "未知昵称",
                        fontSize = 12.sp,
                        color = InstagramDarkGray
                    )
                }
                if (followerUser.id == SessionManager.currentUser?.id) {
                    // 不显示任何按钮
                } else {
//                    val isFollowing by homeViewModel.isFollowing.collectAsState(initial = false)
//                    // 加载关注状态
//                    LaunchedEffect(followerUser) {
//                        coroutineScope.launch(Dispatchers.IO) {
//                            val isFollowingResponse =
//                                homeViewModel.judgeIsFollowed(SessionManager.currentUser?.id!!, followerUser.id)
//                            Log.d("UserPostList", "发送请求获得的isFollowingResponse: $isFollowingResponse")
//                            homeViewModel.updateIsFollowing(isFollowingResponse)
//                        }
//                    }
                    // 如果访问的不是当前用户的粉丝列表，则只显示关注与否的按钮
                    if (viewModel.userId != SessionManager.currentUser?.id) {
                        // 关注与否按钮
                        val isFollowed: Boolean = followerUser.id in viewModel.loginFollowingList.value
                        if (isFollowing) {
                            Button(
                                onClick = {
                                    // 发送取消关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendUnFollowRequest(
                                            followingId = followerUser.id!!,
                                            followerId = SessionManager.currentUser?.id!!
                                        )
                                        homeViewModel.updateIsFollowing(false)
                                    }
                                    Toast.makeText(
                                        context,
                                        "取消关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramLightGray,
                                    contentColor = InstagramDarkGray
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "已关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        } else {
                            Button(
                                onClick = {
                                    // 发送关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendFollowRequest(
                                            followingId = followerUser.id!!,
                                            followerId = SessionManager.currentUser?.id!!
                                        )
                                        homeViewModel.updateIsFollowing(true)
                                    }
                                    Toast.makeText(
                                        context,
                                        "关注成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramBlue,
                                    contentColor = Color.White
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "关注",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }

                    } else {
                        if (isFollowing) {
                            // 移除关注按钮
                            Button(
                                onClick = {
                                    // 发送取消关注请求
                                    coroutineScope.launch(Dispatchers.IO) {
                                        MyRetrofitDatasource.sendUnFollowRequest(
                                            followingId = SessionManager.currentUser?.id!!,
                                            followerId = followerUser.id!!
                                        )
                                        //homeViewModel.updateIsFollowing(false)
                                    }
                                    // 提示已经移除该粉丝
                                    Toast.makeText(
                                        context,
                                        "移除成功",
                                        Toast.LENGTH_SHORT
                                    ).show()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = InstagramLightGray,
                                    contentColor = InstagramDarkGray
                                ),
                                modifier = Modifier
                                    .height(30.dp)
                                    .width(80.dp)
                                    .padding(horizontal = 4.dp), // 减少水平内边距
                                shape = RoundedCornerShape(5.dp),
                                elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                                contentPadding = PaddingValues(
                                    horizontal = 8.dp,
                                    vertical = 0.dp
                                ) // 设置内容内边距
                            ) {
                                Text(
                                    text = "移除",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold
                                )
                            }
                        }
//                        Image(
//                            painter = painterResource(id = R.drawable.options_vertical),
//                            contentDescription = "options",
//                            modifier = Modifier.size(24.dp)
//                        )
                    }
                }
            }
        }
    }
}

@SuppressLint("StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FollowTopBar(
    navController: NavHostController,
    userInfo: UserInfo,
) {
    //val userInfo = viewModel.userInfo.value
    TopAppBar(
        title = {

        },
        navigationIcon = {
            Row(
                modifier = Modifier.padding(end = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        navController.popBackStack()
                    },
                    modifier = Modifier
                        .size(45.dp)
                        .padding(start = 10.dp, end = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.arrow_left),
                        contentDescription = "back",
                        modifier = Modifier
                            .size(30.dp)
                    )
                }
                userInfo.userName?.let {
                    Text(
                        text = it,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
                        modifier = Modifier.padding(top = 10.dp, start = 10.dp)
                    )
                }
            }
        },
        actions = {},
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
            containerColor = Color.Transparent
        )
    )
}